﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _443_Server
{
	public class PlayerUpdating
	{
		public static void UpdatePlayer(Player p)
		{
			p.OutPackets.CreatePacketShort(29);
			UpdateThisMovement(p);
			UpdateOtherPlayers(p);
			AddPlayers(p);
			UpdatePlayerMasks(p);
			p.OutPackets.EndPacketShort();

			p.Teleported = false;
			p.UpdateFlags = 0;
		}

		public static void UpdateThisMovement(Player p)
		{
			p.OutStream.InitBitAccess();
			if (p.Teleported)
			{
				p.OutStream.WriteBits(1, 1); //update movement
				p.OutStream.WriteBits(2, 3); //movement type
				p.OutStream.WriteBits(7, p.Location.LocalX);
				p.OutStream.WriteBits(1, (p.UpdateFlags != 0 ? 1 : 0)); //update required - write 1 for when i want to add some shitty appearance
				p.OutStream.WriteBits(2, p.Location.H);
				p.OutStream.WriteBits(7, p.Location.LocalY);
				p.OutStream.WriteBits(1, 1);
			}
			else if (p.UpdateFlags != 0)
			{
				p.OutStream.WriteBits(1, 1);
				p.OutStream.WriteBits(2, 0);
			}
			else
			{
				p.OutStream.WriteBits(1, 0);
			}
		}

		public static void UpdateOtherPlayers(Player p)
		{
			//No other players for now, so...
			p.OutStream.WriteBits(8, 0);
		}

		public static void AddPlayers(Player p)
		{
			//No other players for now, so...
			p.OutStream.WriteBits(11, 2047);
			p.OutStream.FinishBitAccess();
		}

		public static void UpdatePlayerMasks(Player p)
		{
			if (p.UpdateFlags > 0)
				p.OutStream.WriteByte((byte)p.UpdateFlags); //5th bit is set for short
			if ((p.UpdateFlags & 0x40) != 0) //update appearance
			{
				Stream str = new Stream();
				str.WriteByte(0); //gender
				str.WriteByte(1); //head icon
				str.WriteByte(1); //skull?
				str.WriteWord(0xFFFF); //we're an npc
				str.WriteWord(0); //npc

				for (int i = 0; i < 5; i++)
					str.WriteByte((byte)0);

				str.WriteWord(0x328); // standAnimIndex
				str.WriteWord(0x337); // standTurnAnimIndex
				str.WriteWord(0x333); // walkAnimIndex
				str.WriteWord(0x334); // turn180AnimIndex
				str.WriteWord(0x335); // turn90CWAnimIndex
				str.WriteWord(0x336); // turn90CCWAnimIndex
				str.WriteWord(0x338); // runAnimIndex
				str.WriteQWord(p.EncodedName);
				str.WriteByte(126); // combat

				str.WriteWord(0); //unknown

				p.OutStream.WriteByteA((byte)str.BufferLocation);
				p.OutStream.WriteBytesA(str.Buffer, 0, str.BufferLocation);
			}
		}
	}
}
